package com.example.tool.util.sto;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Collections;

public class SignatureUtils {

    private SignatureUtils() {
        throw new IllegalStateException("SignatureUtils class");
    }

    public static String getSignature(String content, String secretKey) {
        String text = content + secretKey;
        byte[] md5 = DigestUtils.md5(text);
        return Base64.encodeBase64String(md5);
    }

    public static void test() {
        // 1. 准备请求URL
        String url = "https://cloudinter-linkgateway.sto.cn/gateway/link.do";

        // 2. 构建content参数
        JSONObject content = new JSONObject();
        content.put("billCodes", Collections.singletonList("773365408127937"));
        content.put("demandTicketTypeCode", 0);
        content.put("gmtCreateStart", System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
        content.put("gmtCreateEnd", System.currentTimeMillis());
        content.put("pageNum", 1L);
        content.put("pageSize", 100L);
        content.put("statusCode", "0");
        // 可选参数
         content.put("shopKey", "FE74B393757881089702FC691B049011");

        // 3. 构建公共参数
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.add("api_name", "CHAOSHANG_AFTERSALE_QUERY");
        paramsMap.add("from_appkey", "CAKitUhLCDLTpNi"); // 替换为你的appkey
        paramsMap.add("from_code", "CAKitUhLCDLTpNi");   // 替换为你的from_code
        paramsMap.add("to_appkey", "sto_merchant");
        paramsMap.add("to_code", "sto_merchant");
        paramsMap.add("content", content.toString());

        // 4. 生成签名 (appSecret需要替换为你的实际密钥)
        String dataDigest = getSignature(content.toString(), "XlXGViVGxv2WopZ37DNGSLXo5YnOjr3p");
        paramsMap.add("data_digest", dataDigest);

        // 5. 发送请求
        RestTemplate restTemplate = new RestTemplate();
        try {
            restTemplate.getMessageConverters().set(1,
                    new StringHttpMessageConverter(StandardCharsets.UTF_8));
            String response = restTemplate.postForObject(url, paramsMap, String.class);
            System.out.println("接口响应: " + response);


        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
    }


    public static void main(String[] args) {
        test();
    }
}
